const tbody = document.querySelector('tbody');
const addForm = document.querySelector('#addModal form'); // 新增表单
const updateForm = document.querySelector('#updateModal form'); // 新增表单


function getStudentList() {
    axios.get('/student/list')
        .then(result => {
            if (result.data.code === 0) {
                const list = result.data.data
                const html = list.reduce((h, v) => h + `
                <tr>
        <th scope="row">${v.id}</th>
        <td>${v.name}</td>
        <td>${v.age}</td>
        <td>${v.sex}</td>
        <td>${v.group}</td>
        <td>${v.phone}</td>
        <td>${v.salary}</td>
        <td>${v.truesalary}</td>
        <td>${v.province+v.city+v.county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm update-show-modal" data-id="${v.id}">修改</button>
          <button type="button" class="btn btn-danger btn-sm deleteBtn" data-id="${v.id}">删除</button>
        </td>
      </tr>
                `, '')
                tbody.innerHTML=html
        }
    })
}


function render(url,params,dom,label,value='') {
    axios.get(url,{params})
    .then(result => {
       
        dom.innerHTML = result.data.reduce((h, v) => h+`
        <option value="${v}">${v}</option>
        `, `<option value="">--${label}--</option>`)
        dom.value = value
    })
   
}

function init(selector) {
    const provinceSelect = document.querySelector(`${selector} [name=province]`);
    const citySelect = document.querySelector(`${selector} [name=city]`);
    const countySelect = document.querySelector(`${selector} [name=county]`);
   // axios.get('/geo/province')
   //     .then(result => {
          
   //         provinceSelect.innerHTML = result.data.reduce((h, v) => h+`
   //         <option value="${v}">${v}</option>
   //         `, `<option value="">--省--</option>`)
   //     })
       render('/geo/province',{},provinceSelect,"省")
   
   provinceSelect.addEventListener("change", function () {
       // axios.get('/geo/city',{params:{pname:provinceSelect.value}})
       // .then(result => {
          
       //     citySelect.innerHTML = result.data.reduce((h, v) => h+`
       //     <option value="${v}">${v}</option>
       //     `, `<option value="">--市--</option>`)
       // })
       render('/geo/city',{pname:provinceSelect.value},citySelect,"市")
   })
       
   citySelect.addEventListener("change", function () {
       // const params= {
       //     pname: provinceSelect.value,
       //     cname:citySelect.value
       // }
       // axios.get('/geo/county',{params})
       // .then(result => {
          
       //     countySelect.innerHTML = result.data.reduce((h, v) => h+`
       //     <option value="${v}">${v}</option>
       //     `, `<option value="">--县--</option>`)
       // })
       render('/geo/county',{pname:provinceSelect.value,cname:citySelect.value},countySelect,"县")
   
   })
       
   
}
getStudentList()
init("#addModal")
init("#updateModal")

addForm.addEventListener("submit", function (e) {
    e.preventDefault()
    const data = $(addForm).serialize()
    axios.post('/student/add', data)
        .then(result => {
            if (result.data.code === 0) {
                toastr.success(result.data.message)
                addForm.reset()
                $('#addModal').modal('hide')
                getStudentList()
        }
    })
})

tbody.addEventListener("click", function (e) {
    const dom = e.target
    if (dom.classList.contains('update-show-modal')) {
        $('#updateModal').modal('show')
        const id = dom.dataset.id;
        // 根据id 来发送请求 获取对应数据
        axios.get('/student/one', { params: { id } }).then((result) => {
          // console.
          // 获取 对象
          const obj = result.data.data;
    
          // 大功能 把对象数据 显示在 form标签中  start
          for (const key in obj) {
            // 根据key 去查找对应的dom元素
            const target = document.querySelector(`#updateModal [name=${key}]`);
    
            // 性别  单选框  特殊！！
            if (key === 'sex') {
              // 根据 当前 性别的值 (obj.sex ) 找到 对应的 性别 单选框  让它选中
              // 既要找到 name = sex 而且 value = obj.sex 标签
              document.querySelector(
                `#updateModal [name=sex][value=${obj.sex}]`
              ).checked = true;
              continue; // 跳过下面的代码
            }
    
            // 当找到了这个dom元素 我们才可以设置  给普通的表单元素使用
            if (target) {
              target.value = obj[key];
            }
          }
            render('/geo/city', { pname: obj.province }, document.querySelector(`#updateModal [name=city]`), "市", obj.city)
            render('/geo/county',{pname:obj.province,cname:obj.city},document.querySelector(`#updateModal [name=county]`),"市",obj.county)
          // 大功能 把对象数据 显示在 form标签中  end
        });
    } else if (dom.classList.contains('deleteBtn')) {
        if (confirm('确定删除')) {
            const id=dom.dataset.id
            axios.delete('/student/delete', { params: { id } })
                .then(result => {
                    if (result.data.code === 0) {
                        toastr.success(result.data.message)
                        getStudentList()
                }
            })
        }
      }
});
    

updateForm.addEventListener("submit", function (e) {
    e.preventDefault()
    const data = $(updateForm).serialize()
    axios.put('/student/update', data)
        .then(result => {
            if (result.data.code === 0) {
                toastr.success(result.data.message)
                updateForm.reset()
                $('#updateModal').modal('hide')
                getStudentList()
        }
    })
})